<?php
namespace app\api\controller;

use app\exception\ApiException;
use app\index\model\UserModel;
use think\admin\Controller;
use Omnipay\Omnipay;
use think\exception\HttpException;

/**
 * Class Index
 * @package app\index\controller
 */
class Base extends Controller
{
    public $token = '';
    public $user = null;
    public $token_login_info = null;

    public function __construct(\think\App $app)
    {
        parent::__construct($app);
        // 获取请求头中的Bearer
        $token = request()->header('Authorization');
        if($token){
            $token = str_replace('Bearer ', '', $token);
        }
        // $token = request()->header('token');
        


        $this->token = $token;
        if($token){
            $login_info = cache($token);
            if($login_info){
                $this->token_login_info = $login_info;
                $this->user = $login_info['user'];
            }
            if($token == 'SWGf414y9OFeBn2amzbMatxkPgU9d6Vx'){
                $this->user = UserModel::cache(3600)->find(1);
            }
        }else{
            if(env('env.local_uid')){
                $this->user = UserModel::cache(3600)->find(env('env.local_uid'));
            }
        }
    }


    public function checkIsAdmin(){
        // in_array 不能判断大小写
        return in_array('Admin', $this->user->roles);
    }


    /**
     * 检测当前用户是否已登录
     * @return mixed
     */
    public function checkUserLogin(){
        if($this->user == null){
            throw new ApiException('用户登录失效，请登录后重试', '402');
        }
    }

    /**
     * 通用返回成功方法
     * @return mixed
     */
    public function returnSuccess($data, $message = 'success', $code = 200){

        // 这里兼容一下admin-plus。如果是返回的列表。page里边的total。把他在外层也创建一个
        
        if(isset($data['page']['total'])){
            $data['total'] = $data['page']['total'];
        }
        return json(['code' => $code, 'msg' => $message, 'data' => $data]);
    }

    public function returnError($data, $message = 'success', $code = 500){
        return json(['code' => $code, 'msg' => $message, 'data' => $data]);
    }

}